package com.app.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.app.common.Result;
import com.app.common.SignInContinuous;
import com.app.model.*;
import com.app.service.IIntegralRuleLogService;
import com.app.service.IIntegralRuleService;
import com.app.service.ISignInService;
import com.app.service.UserService;
import com.app.utils.TokenUtils;
import com.app.vo.IntegralRuleLogVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 * 用户签到积分规则表 前端控制器
 * </p>
 *
 * @author yoominic
 * @since 2023-12-09
 */
@RestController
@RequestMapping("/integralRule")
public class IntegralRuleController {
    private static final Logger log = LoggerFactory.getLogger(IntegralRuleController.class);
    @Autowired
    private IIntegralRuleService iIntegralRuleService;
    @Autowired
    private ISignInService iSignInService;
    @Autowired
    private UserService userService;
    @Autowired
    private IIntegralRuleLogService iIntegralRuleLogService;





    /**
     * 积分规则修改日志列
     * @param integralRuleId
     * @return
     */
    @GetMapping("/admin/getIntegralRuleLogList")
    public Result getIntegralRuleLogList(Integer page, Integer limit,String integralRuleId) {
        IntegralRuleLogVo vo = iIntegralRuleLogService.getIntegralRuleLogList(page,limit,integralRuleId);
        return Result.success(vo);
    }


    /**
     * 插入积分规则
     *
     * @param integralRule 积分规则
     * @return {@link Result}
     */
    @PostMapping("/admin/insertIntegralRule")
    public Result insertIntegralRule(HttpServletRequest request,@RequestBody IntegralRule integralRule) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        if (integralRule.getId() != null && integralRule.getId() > 0) {
            integralRule.setUpdateTime(LocalDateTime.now());

            //储存修改记录日志
            IntegralRule oldInfo =  iIntegralRuleService.getById(integralRule.getId());
            IntegralRuleLog logInfo = new IntegralRuleLog();
            logInfo.setUserId(Integer.parseInt(userId));
            logInfo.setIntegralRuleId(integralRule.getId());

            // 将InviteConfigModel对象转换为JSON字符串
            // PrettyFormat用于格式化输出，使其更易于阅读
            String oldJsonStr = JSON.toJSONString(oldInfo, SerializerFeature.PrettyFormat);
            logInfo.setOldJsonstr(oldJsonStr);
            String newJsonStr = JSON.toJSONString(integralRule, SerializerFeature.PrettyFormat);
            logInfo.setNewJsonstr(newJsonStr);

            logInfo.setCreateTime(LocalDateTime.now());
            iIntegralRuleLogService.save(logInfo);

            return Result.success(this.iIntegralRuleService.updateById(integralRule));
        } else {
            integralRule.setCreateTime(LocalDateTime.now());
            return Result.success(this.iIntegralRuleService.save(integralRule));
        }
    }

    /**
     * 删除积分规则
     *
     * @param id id
     * @return {@link Result}
     */
    @GetMapping("/admin/deleteIntegralRule")
    public Result deleteIntegralRule(Long id) {
        IntegralRule integralRule = iIntegralRuleService.getById(id);
        integralRule.setStatus(0);
        return Result.success(iIntegralRuleService.updateById(integralRule));
    }

    /**
     * 获取积分规则列表
     *
     * @return {@link Result}
     */
    @GetMapping("/admin/getIntegralRuleList")
    public Result getIntegralRuleList() {
        return Result.success(iIntegralRuleService.list());
    }

    /**
     * 按id选择积分规则
     *
     * @param id id
     * @return {@link Result}
     */
    @GetMapping("/admin/selectIntegralRuleById")
    public Result selectIntegralRuleById(Long id) {
        return Result.success(iIntegralRuleService.getById(id));
    }

    /**
     * 小程序:获取积分规则
     *
     * @return {@link Result}
     */
    @GetMapping("/getIntegralRule")
    public Result getIntegralRule(HttpServletRequest request) throws ParseException {
        String token = request.getHeader("token");
        QueryWrapper<IntegralRule> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        queryWrapper.last("limit 1");
        IntegralRule one = this.iIntegralRuleService.getOne(queryWrapper);
        if (token != null) {
            String openId = TokenUtils.verify(token);
            UserModel userModel = userService.getUserByOpenid(openId);
            if (userModel != null) {
                QueryWrapper<SignIn> signInQueryWrapper = new QueryWrapper<>();
                signInQueryWrapper.select("create_time");
                signInQueryWrapper.eq("user_id", userModel.getId());
                signInQueryWrapper.orderByDesc("create_time");
                List<SignIn> signInList = iSignInService.list(signInQueryWrapper);
                int continuousSignInDay = SignInContinuous.getContinuousSignInDay(signInList);
                if (continuousSignInDay != 0 && continuousSignInDay % one.getContinueSignDay() == 0) {
                    String today = DateUtil.today();
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    String formattedDateTime = signInList.get(0).getCreateTime().format(formatter);
                    if (today.equals(formattedDateTime)) {
                        one.setContinuousSignInDay(one.getContinueSignDay());
                    }else {
                        one.setContinuousSignInDay(continuousSignInDay % one.getContinueSignDay());
                    }

                } else {
                    if (continuousSignInDay % one.getContinueSignDay() != 0) {
                        one.setContinuousSignInDay(continuousSignInDay % one.getContinueSignDay());
                    } else {
                        one.setContinuousSignInDay(continuousSignInDay);
                    }
                }
            }
        }
        return Result.success(one);
    }
}

